//
//  PayMoneyViewController.m
//  WheatPlan
//
//  Created by 王晨辉 on 15/6/2.
//  Copyright (c) 2015年 IOSTeam. All rights reserved.
//

#import "PayMoneyViewController.h"
#import "DataSigner.h"
#import "Order.h"
#import <AlipaySDK/AlipaySDK.h>

@interface PayMoneyViewController ()

@end

@implementation PayMoneyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置导航栏头文字
    self.navigationItem.title = @"支付";
    //设置导航栏背景颜色
    [self.navigationController.navigationBar setBarTintColor:[GetFileModel colorWithHexString:@"#44afd7" alpha:1]];
    //设置导航栏字体颜色
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    self.view.backgroundColor = UIColorWithRGBA(240, 239, 245, 1);
    
    
    //自定义左右按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"_0000_返回.png"]
                      forState:UIControlStateNormal];
    [button addTarget:self action:@selector(turntolast)
     forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(0, 0, 20, 15);
    
    UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    self.navigationItem.leftBarButtonItem = menuButton;
    
    [self subView];
    
}


-(void)turntolast{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    
}
-(void)subView{
    
    
    UIImageView * image = [[UIImageView alloc]init];
    image.frame = CGRectMake(0, NavbarHight, SCREEN_WIDTH, SCREEN_HEIGHT/4.3+25);
    image.image = [UIImage imageNamed:@"_0001_圆角矩形-2"];
    [self.view addSubview:image];
    
    UILabel * moneyLab = [[UILabel alloc]initWithFrame:CGRectMake(0, NavbarHight+10, SCREEN_WIDTH, SCREEN_HEIGHT/4.3)];
    moneyLab.text = [NSString stringWithFormat:@"%@元",self.priceStr];
    moneyLab.textColor = [UIColor orangeColor];
    moneyLab.font = [UIFont systemFontOfSize:35];
    moneyLab.textAlignment = NSTextAlignmentCenter;
    moneyLab.numberOfLines = 1;
    [self.view addSubview:moneyLab];
    
    UIImageView * imageView = [[UIImageView alloc]init];
    imageView.frame = CGRectMake(0, 230, SCREEN_WIDTH, SCREEN_HEIGHT-230);
    imageView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:imageView];
    
    UILabel * nameLab = [[UILabel alloc]initWithFrame:CGRectMake(15, 10, SCREEN_WIDTH, 30)];
    nameLab.text = @"同城解读报名";
    nameLab.textColor = [UIColor blackColor];
    nameLab.font = [UIFont systemFontOfSize:14];
    nameLab.textAlignment = NSTextAlignmentLeft;
    nameLab.numberOfLines = 1;
    [imageView addSubview:nameLab];
    
    UILabel * payMoney = [[UILabel alloc]initWithFrame:CGRectMake(15, 50, SCREEN_WIDTH, 30)];
    payMoney.text = @"请选择支付方式";
    payMoney.textColor = [UIColor blackColor];
    payMoney.font = [UIFont systemFontOfSize:14];
    payMoney.textAlignment = NSTextAlignmentLeft;
    payMoney.numberOfLines = 1;
    [imageView addSubview:payMoney];
    
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 45, SCREEN_WIDTH, 1)];
    lineView.backgroundColor = UIColorWithRGBA(215, 215, 215, 1);
    [imageView addSubview:lineView];
    
    
    UIButton * payBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    payBtn.frame = CGRectMake(20, 90, 80, 32);
    [payBtn setBackgroundImage:[UIImage imageNamed:@"支付宝@2x.png.png"] forState:UIControlStateNormal];
    [imageView addSubview:payBtn];
    
    
    
    
    
    UIButton * nowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    nowBtn.frame = CGRectMake(0, SCREEN_HEIGHT-60, SCREEN_WIDTH, 60);
//    nowBtn.backgroundColor = UIColorWithRGBA(246, 93, 47, 1);
    [nowBtn addTarget:self action:@selector(got:) forControlEvents:UIControlEventTouchUpInside];
    [nowBtn setTitle:@"确认支付" forState:UIControlStateNormal];
    [nowBtn setBackgroundImage:[UIImage imageNamed:@"red@2x"] forState:UIControlStateNormal];
    [nowBtn setBackgroundImage:[UIImage imageNamed:@"redScl@2x"] forState:UIControlStateHighlighted];
    nowBtn.titleLabel.font = [UIFont systemFontOfSize:24];
    [nowBtn setTintColor:[UIColor whiteColor]];
    [self.view addSubview:nowBtn];
    
    
    
    
    
    
}
-(void)got:(UIButton *)send{
    
    
    NSString *partner = PartnerID;
    NSString *seller = SellerID;
    NSString *privateKey = PartnerPrivKey;
    //partner和seller获取失败,提示
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = [self generateTradeNO]; //订单ID（由商家自行制定）
    order.productName = @"这个也就2块钱"; //商品标题
    order.productDescription = @"看看能不能用而已"; //商品描述
    order.amount = [NSString stringWithFormat:@"%d",[self.priceStr integerValue]]; //商品价格
    order.notifyURL =  @"http://www.xxx.com"; //回调URL
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"maimiaogongxue";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    ////NSLog(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            ////NSLog(@"reslut ================ %@",resultDic);
            if ([resultDic[@"resultStatus"]isEqualToString:@"9000"]) {
                [self ShowProgressHUDwithMessage:@"支付成功"];
                
                
            }else
            {
                [self ShowProgressHUDwithMessage:@"支付失败"];
            }
            //         ////NSLog(@"reslut ================ %@",resultDic[@"memo"]);
        }];
    }
    
    

    
    
    
}
#pragma mark - HUD
- (void)ShowProgressHUDwithMessage:(NSString *)msg
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = msg;
    hud.dimBackground = NO;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:1];
}

- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand(time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
